<?php
require_once 'phpmoko/lib/common.php';

class MySQL
{
	private $mysqli = null;
	private $showSQL = false;
	private $server;
	private $username;
	private $password;
	private $database_name;
	private $persistent = false;
	private $port = 3306;

	function __construct($server, $username, $password, $database_name, $persistent = true, $port = 3306)
	{
		$this->server = $server;
		$this->username = $username;
		$this->password = $password;
		$this->database_name = $database_name;
		$this->persistent = $persistent;
		$this->port = $port;
	}

	function __destruct()
	{
		if (!$this->persistent && ($this->mysqli != null))
			$this->mysqli->close();
	}

	/**
	 *
	 * @return mysqli
	 */
	function getMySQLi()
	{
		if ($this->mysqli == null) {
			if ($this->persistent)
				$this->mysqli = new mysqli("p:" . $this->server, $this->username, $this->password, $this->database_name, (int)$this->port);
			else
				$this->mysqli = new mysqli($this->server, $this->username, $this->password, $this->database_name, (int)$this->port);

			if ($this->mysqli->connect_error) {
				echo 'Connect Error (' . $this->mysqli->connect_errno . ') ' . $this->mysqli->connect_error;
				exit();
			}

			$this->mysqli->query("SET CHARACTER SET 'utf8'");
		}

		return $this->mysqli;
	}

	function showSQL($showSQL)
	{
		$this->showSQL = $showSQL;
	}

	/**
	 *
	 * @param MySQLCommand $command
	 * @return MySQLDataResult
	 */
	function query($command)
	{
		$mysql = $this->getMySQLi();
		$command->setMySQL($mysql);
		$query = $command->generateSQL();

		if (!($result = $mysql->query($query))) {
			require_once 'phpmoko/utils/Console.php';
			Console::error($mysql->error . ' (' . $mysql->errno . ')');
			$result = null;
		}

		if ($this->showSQL) {
			require_once 'phpmoko/utils/Console.php';
			Console::debug($query);
		}

		require_once 'phpmoko/db/MySQLDataResult.php';

		return new MySQLDataResult($mysql, $result);
	}

	function insertId()
	{
		return $this->getMySQLi()->insert_id;
	}
}
?>